<template>
  <div class="login-page flex-center-center">
    <div class="log-box">
      <el-select v-model="language" placeholder="请选择" @change="onSetLanguage">
        <el-option label="中文" value="zh" />
        <el-option label="英文" value="en" />
      </el-select>
      <el-form :model="formModel" :rules="rules" label-position='right' label-width="auto" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formModel.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formModel.password" type="password" placeholder="请输入" show-password
            @keyup.enter="onLogin" />
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button @click="reset">{{ $t('msg.login.resetBtn') }}</el-button>
        <el-button type="primary" @click="onLogin">{{ $t('msg.login.loginBtn') }}</el-button>
      </div>
      <div v-html="$t('msg.login.desc')"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue"
import md5 from 'md5'
import { storeToRefs } from "pinia"
// import { ElMessage } from "element-plus"
import { useI18n } from 'vue-i18n'
import { login } from '@/api'
import { userInfoStore } from "@/stores/userInfo"
import { useLanguageStore } from '@/stores/language'
import router from "@/router"
import { ElMessage } from "element-plus"
const { setToken } = userInfoStore()
const { language } = storeToRefs(useLanguageStore())
const { setLanguage } = useLanguageStore()

const onSetLanguage = (value) => {
  i18n.locale.value = value
  setLanguage(value)
}
const i18n = useI18n()
const formRef = ref(null)
const formModel = ref({
  username: 'super-admin',
  password: '123456'
})
const rules = ref({
  username: [
    { required: true, message: computed(() => i18n.t('msg.login.usernameRule')) }
  ],
  password: [
    { required: true, message: computed(() => i18n.t('msg.login.passwordRule')) }
  ]
})

const onLogin = () => {
  formRef.value.validate(valid => {
    if (valid) {
      login({
        ...formModel.value,
        password: md5(formModel.value.password)
      })
        .then((res) => {
          setToken(res.token)
          ElMessage
          // ElMessage.success('登录成功')
          router.push({ path: '/' })
        })
    }
  })
}

const reset = () => {
  formRef.value.resetFields()
}

</script>

<style lang="scss" scoped>
.login-page {
  width: 100vw;
  height: 100vh;
}

.log-box {
  padding: 20px;
  border: 1px solid #666666;
  border-radius: 6px;
  width: 20%;
  height: 50%;
}
</style>
